<template>
  <view class="uni-combox" :class="border ? '' : 'uni-combox__no-border'">
    <view class="uni-combox__input-box">
      <input
        :class="inputVal ? 'uni-combox__input' : 'placeholder-class'"
        :placeholder="placeholder"
        v-model="inputVal"
        @input="onInput"
        @focus="onFocus"
        @blur="onBlur"
        type="number"
      />
      <uni-icons
        :type="showSelector ? 'top' : 'bottom'"
        size="14"
        color="#999"
        @click="toggleSelector"
        v-if="border"
      >
      </uni-icons>
    </view>
    <view class="uni-combox__selector" v-if="showSelector">
      <view class="uni-popper__arrow"></view>
      <scroll-view scroll-y="true" class="uni-combox__selector-scroll">
        <view
          class="uni-combox__selector-empty"
          v-if="filterCandidatesLength === 0"
        >
          <text>{{ emptyTips }}</text>
        </view>
        <view
          class="uni-combox__selector-item"
          v-for="(item, index) in filterCandidates"
          :key="index"
          @click="onSelectorClick(index)"
        >
          <text>{{ item }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { debounce } from "@/common/common.js";
import { getFunds } from "@/apis/api";

export default {
  name: "fund-Input",
  props: {
    border: {
      type: Boolean,
      default: true,
    },
    placeholder: {
      type: String,
      default: "",
    },
    emptyTips: {
      type: String,
      default: " ",
    },
    // #ifndef VUE3
    value: {
      type: String,
      default: "",
    },
    // #endif
    // #ifdef VUE3
    modelValue: {
      type: String,
      default: "",
    },
    // #endif
    fundId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      isFocused: false,
      hfundItemList: [],
      candidates: [],
      showSelector: false,
      inputVal: "",
      fundIdVal: "",
    };
  },
  computed: {
    filterCandidates() {
      return this.candidates.filter((item) => {
        return true;
      });
    },
    filterCandidatesLength() {
      return this.filterCandidates.length;
    },
  },
  watch: {
    // #ifndef VUE3
    value: {
      handler(newVal) {
        this.inputVal = newVal;
      },
      immediate: true,
    },
    // #endif
    // #ifdef VUE3
    modelValue: {
      handler(newVal) {
        this.inputVal = newVal;
      },
      immediate: true,
    },
    // #endif
    fundId: {
      handler(newVal) {
        this.fundIdVal = newVal;
      },
      immediate: true,
    },
    candidates: {
      handler(newVal) {
        if (
          newVal &&
          newVal.length > 0 &&
          this.isFocused &&
          !this.showSelector
        ) {
          this.showSelector = true;
        } else if ((!newVal || newVal.length == 0) && this.showSelector) {
          this.showSelector = false;
        }
      },
      immediate: true,
    },
  },
  created() {
    this.fundIdVal = this.fundId;
  },
  methods: {
    toggleSelector() {
      this.showSelector = !this.showSelector;
    },
    onFocus() {
      this.isFocused = true;
      if (this.inputVal) {
        this.showSelector = true;
      }
    },
    onBlur() {
      this.isFocused = false;
      setTimeout(() => {
        this.showSelector = false;
      }, 153);
    },
    onSelectorClick(index) {
      this.inputVal = this.filterCandidates[index];
      this.showSelector = false;

      let item = this.getfundId();
      this.setfundId(item);

      // #ifndef VUE3
      this.$emit("input", this.inputVal);
      // #endif
      // #ifdef VUE3
      this.$emit("update:modelValue", this.inputVal);
      // #endif
    },

    getCandidates() {
      let index = this.inputVal.trim().indexOf(" ");
      let keywords = this.inputVal.trim();
      if (!keywords) {
        this.hfundItemList = [];
        this.candidates = [];
        setTimeout(() => {}, 153);
      } else {
        var para = {
          pageSize: 10,
          keywords: keywords,
        };

        getFunds(para)
          .then((res) => {
            var newItems = [];
            this.hfundItemList = [];
            res.data.data.forEach((e) => {
              this.hfundItemList.push({
                fundId: e.fundId,
                name: e.name,
              });
              newItems.push(`[${e.level}]${e.name}`);
            });
            this.candidates = newItems;
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
    getfundId() {
      let keywords = this.inputVal.trim();
      return this.hfundItemList.find((x) => x.name == keywords);
    },
    setfundId(item) {
      let newVal = item ? item.fundId : "";

      if (this.fundIdVal !== newVal) {
        if (item) {
          this.hfundItemList = [item];
          this.candidates = [`${item.name}`];
        }
        this.fundIdVal = newVal;
        this.$emit("update:fundId", this.fundIdVal);
      }
    },
    onInput() {
      let item = this.getfundId();
      if (!item) {
        debounce(() => {
          this.getCandidates();
        }, 400);
      }
      this.setfundId(item);

      setTimeout(() => {
        // #ifndef VUE3
        this.$emit("input", this.inputVal);
        // #endif
        // #ifdef VUE3
        this.$emit("update:modelValue", this.inputVal);
        // #endif
      });
    },
    getFundName() {
      let item = this.getfundId();
      return item?.name;
    },
  },
};
</script>

<style lang="scss" scoped>
.uni-combox {
  font-size: 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 6px 10px;
  position: relative;
  flex-direction: row;
  align-items: center;
}

.uni-combox__label {
  font-size: 16px;
  line-height: 22px;
  padding-right: 10px;
  color: #999999;
}

.uni-combox__input-box {
  position: relative;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex: 1;
  flex-direction: row;
  align-items: center;
}

.uni-combox__input {
  flex: 1;
  font-size: 14px;
  height: 22px;
  line-height: 22px;
}

.placeholder-class {
  flex: 1;
  color: #999;
  font-size: 12px;
}

.uni-combox__selector {
  /* #ifndef APP-NVUE */
  box-sizing: border-box;
  /* #endif */
  position: absolute;
  top: calc(100% + 12px);
  left: 0;
  width: 100%;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 4;
  padding: 4px 0;
}

.uni-combox__selector-scroll {
  /* #ifndef APP-NVUE */
  max-height: 200px;
  box-sizing: border-box;
  /* #endif */
}

.uni-combox__selector-empty,
.uni-combox__selector-item {
  /* #ifndef APP-NVUE */
  display: flex;
  cursor: pointer;
  /* #endif */
  line-height: 36px;
  font-size: 14px;
  text-align: center;
  // border-bottom: solid 1px #DDDDDD;
  padding: 0px 10px;
}

.uni-combox__selector-item:hover {
  background-color: #f9f9f9;
}

.uni-combox__selector-empty:last-child,
.uni-combox__selector-item:last-child {
  /* #ifndef APP-NVUE */
  border-bottom: none;
  /* #endif */
}

// picker 弹出层通用的指示小三角
.uni-popper__arrow,
.uni-popper__arrow::after {
  position: absolute;
  display: block;
  width: 0;
  height: 0;
  border-color: transparent;
  border-style: solid;
  border-width: 6px;
}

.uni-popper__arrow {
  filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
  top: -6px;
  left: 10%;
  margin-right: 3px;
  border-top-width: 0;
  border-bottom-color: #ebeef5;
}

.uni-popper__arrow::after {
  content: " ";
  top: 1px;
  margin-left: -6px;
  border-top-width: 0;
  border-bottom-color: #fff;
}

.uni-combox__no-border {
  border: none;
}
</style>
